package com.ccsoft.atools.service;

import com.ccsoft.atools.dao.Vue3menuMapper;
import com.ccsoft.atools.model.Vue3menu;
import com.ccsoft.atools.model.Vue3menuNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class Vue3menuServiceImpl implements Vue3menuService {
    @Autowired
    private Vue3menuMapper dao;

    @Override
    public List<Vue3menuNode> buildNode() {
        List<Vue3menuNode> list = selectAllNode();
        List<Vue3menuNode> collect = list.stream().filter(m -> m.getParent_id() == 0).map(
                (m) -> {
                    m.setChildren(getChildrens(m, list));
                    return m;
                }
        ).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<Vue3menu> selectAll() {
        return dao.selectAll();
    }

    @Override
    public List<Vue3menuNode> selectAllNode() {
        List<Vue3menu> list = selectAll();
        if (list.size() <= 0) return null;
        List<Vue3menuNode> ret = new ArrayList<>();
        list.forEach(item -> ret.add(new Vue3menuNode(item)));
        return ret;
    }

    /**
     * 2021年9月23日 12:54:54 chanchaw
     * 返回没有 root 的菜单数组
     *
     * @return
     */
    @Override
    public List<Vue3menuNode> buildMenus() {
        List<Vue3menuNode> withRootMenus = buildNode();// 带有根的菜单项树形结构数据
        if (withRootMenus.size() <= 0) return withRootMenus;
        return withRootMenus.get(0).getChildren();
    }

    private List<Vue3menuNode> getChildrens(Vue3menuNode root, List<Vue3menuNode> all) {
        List<Vue3menuNode> children = all.stream().filter(m -> {
            return Objects.equals(m.getParent_id(), root.getId());
        }).map(
                (m) -> {
                    m.setChildren(getChildrens(m, all));
                    return m;
                }
        ).collect(Collectors.toList());
        return children;
    }
}
